<template>
  <div class="form-container">
    <!-- 标题 -->
    <h2 class="table-title1">从业人员安全教育培训档案</h2>
    <el-button
      type="primary"
      @click="exportToExcel"
      class="export-button"
    >
      导出数据
    </el-button>

    <el-form ref="form" :data="formData" label-width="80px" label-height="20px" class="form" :disabled="true">
      <!-- 表单内容 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位">
            <el-input v-model="formData.company"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="学历">
            <el-input v-model="formData.education"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别">
            <el-radio-group v-model="formData.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="出生年月">
            <el-date-picker v-model="formData.birthDate" type="date" style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作时间">
            <el-date-picker v-model="formData.workStartDate" type="date" style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门">
            <el-input v-model="formData.deptName" style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-input v-model="formData.postName" style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="技术职称">
            <el-input v-model="formData.technicalTitle" style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="技能等级">
            <el-input v-model="formData.technicalLevel" style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="专业">
        <el-input v-model="formData.major"></el-input>
      </el-form-item>

      <el-form-item label="证书获取情况">
        <el-input v-model="formData.certificates"></el-input>
      </el-form-item>
    </el-form>
    <div class="table-title">
      <h3>培训记录</h3>
    </div>
    <!-- 表格部分 -->
    <el-table :data="trainingList" class="training-table" border :style="{ 'max-height': '400px', 'overflow-y': 'auto' }">
      <!--      <el-table-column label="培训日期" prop="trainingDate" :show-overflow-tooltip="true"></el-table-column>-->
      <!--      <el-table-column label="培训内容" prop="trainingContent" :show-overflow-tooltip="true"></el-table-column>-->
      <!--      <el-table-column label="培训方式" prop="trainingMethod" :show-overflow-tooltip="true"></el-table-column>-->
      <!--      <el-table-column label="培训层级" prop="trainingLevel" :show-overflow-tooltip="true"></el-table-column>-->
      <!--      <el-table-column label="考核结果" prop="evaluationResult" :show-overflow-tooltip="true"></el-table-column>-->

      <!--      <el-table-column label="培训标题" align="center" prop="title" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column label="人员" align="center" prop="userName" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column label="人员" align="center">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ getUserName(scope.row.userId) }}</span> &lt;!&ndash; 使用计算属性或方法获得用户名 &ndash;&gt;-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="培训日期" align="center" prop="trainingTime" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训内容" align="center">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="removeHtmlTags(scope.row.trainingContent)"
            placement="top"
          >
            <div
              style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
            >
              {{ removeHtmlTags(scope.row.trainingContent) }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <!-- 展开行 -->
      <el-table-column label="详细内容" type="expand" width="80">
        <template slot-scope="props">
          <div style="padding: 10px; max-width: 500px; word-wrap: break-word;">
            <strong>详细内容:</strong>
            <p><span v-html="props.row.trainingContent"></span></p>
          </div>
        </template>
      </el-table-column>


      <el-table-column label="培训方式" align="center" prop="trainingMethod" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.training_method" :value="scope.row.trainingMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="培训层级" align="center" prop="trainingLevel" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.training_level" :value="scope.row.trainingLevel"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="文件路径" align="center" prop="filePath" />-->
      <!--      <el-table-column label="考核结果" align="center" prop="result" :show-overflow-tooltip="true">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.assessment_result" :value="scope.row.result"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 考试记录表格部分 -->
    <div class="table-title">
      <h3>考试记录</h3>
    </div>
    <el-table :data="examRecords" class="training-table" border :style="{ 'max-height': '400px', 'overflow-y': 'auto' }">
      <el-table-column label="考试日期" align="center" prop="createTime" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <span>{{  scope.row.taskExamPaperAnswer.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="试卷名称" align="center" prop="paperName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
           {{ scope.row.taskExamPaperAnswer.paperName }}
           </span>
        </template>
      </el-table-column>
<!-- 考试分数、试卷分数、答对题目数量、总题目数量、耗时（秒）、答题试卷内容 -->
      <el-table-column label="考试分数" align="center" prop="taskExamPaperAnswer.userScore" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
            {{ scope.row.taskExamPaperAnswer.userScore }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="试卷分数" align="center" prop="taskExamPaperAnswer.paperScore" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
            {{ scope.row.taskExamPaperAnswer.paperScore }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="答对题目数量" align="center" prop="taskExamPaperAnswer.questionCorrect" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
            {{ scope.row.taskExamPaperAnswer.questionCorrect }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="总题目数量" align="center" prop="taskExamPaperAnswer.questionCount" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
            {{ scope.row.taskExamPaperAnswer.questionCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="耗时（秒）" align="center" prop="taskExamPaperAnswer.doTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.taskExamPaperAnswer !== null">
            {{ scope.row.taskExamPaperAnswer.doTime }}
          </span>
        </template>
      </el-table-column>
<!--      <el-table-column label="答题试卷内容" align="center" prop="taskExamPaperAnswer.paperAnswer" :show-overflow-tooltip="true" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.taskExamPaperAnswer !== null">-->
<!--            <el-tooltip-->
<!--              class="item"-->
<!--              effect="dark"-->
<!--              :content="removeHtmlTags(scope.row.taskExamPaperAnswer.paperAnswer)"-->
<!--              placement="top"-->
<!--            >-->
<!--              <div-->
<!--                style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"-->
<!--              >-->
<!--                {{ removeHtmlTags(scope.row.taskExamPaperAnswer.paperAnswer) }}-->
<!--              </div>-->
<!--            </el-tooltip>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    <!-- 考试记录分页 -->
    <pagination
      v-show="totalExamRecords > 0"
      :total="totalExamRecords"
      :page.sync="examQueryParams.pageNum"
      :limit.sync="examQueryParams.pageSize"
      @pagination="getExamRecords"
    />
  </div>
</template>

<script>
import {listTraining} from "@/api/exam/training";
import {getUser, getUserProfile} from "../../../api/system/user";
import {detailList} from "@/api/exam/task";
import store from "@/store";
import * as XLSX from "xlsx"; // 导入 xlsx
import {saveAs} from "file-saver"; // 如果使用 file-saver 保存文件
export default {
  name: "Training",
  dicts: ['training_level', 'training_method', 'assessment_result', 'technical_title', 'technical_level', 'education'],
  data() {
    return {
      // 总条数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
         userId: -1,
      },
      // 表单绑定的数据
      formData: {
        company: '', // 单位
        name: '', // 姓名
        education: '', // 学位
        gender: '', // 性别
        birthDate: '', // 出生年月
        workStartDate: '', // 工作时间
        major: '', // 专业
        certificates: '', // 证书获取情况
        deptName: '', // 部门
        postName: '', // 岗位
        technicalTitle: '', // 技术职称
        technicalLevel: '', // 技术职称级别

      },
      // 其他数据...
      examQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      examRecords: [], // 存储考试记录数据
      totalExamRecords: 0, // 存储考试记录总数
      trainingList: []
    };
  },
  created() {
  },
  mounted() {
    this.queryParams.userId=this.$route.query.userId;
    console.log('页面传递userId',this.queryParams.userId);
    this.getUserByUserId(this.queryParams.userId)
  },

  methods: {
    // 获取列表
    getList() {
      listTraining(this.queryParams).then(response => {
        console.log('trainingList列表', response);
        this.trainingList = response.rows;
        this.total = response.total;
      });
    },
    getExamRecords() {
      detailList(this.examQueryParams).then(response => {
        console.log('考试记录列表', response);
        //过滤taskStatus为1的记录
        this.examRecords = response.rows.filter(item => item.taskStatus === 1);
        this.totalExamRecords = response.total; // 更新总条数
      });
    },
    //获取用户信息
    getUserInfor() {

      // 获取当前用户
      getUserProfile().then(responseData => {
        console.log('userProfile', responseData);
        this.formData.company = responseData.data.company; // 单位
        this.formData.name = responseData.data.nickName; // 姓名
        this.formData.gender = responseData.data.sex === '0' ? '男' : '女'; // 性别
        this.formData.birthDate = responseData.data.birthDate; // 出生年月
        this.formData.workStartDate = responseData.data.workDate; // 工作时间
        this.formData.deptName = responseData.data.dept.deptName; // 部门
        this.formData.postName = responseData.postGroup; // 岗位
        this.formData.major = responseData.data.major; // 专业
        this.formData.certificates = responseData.data.certificate; // 证书获取情况
        //根据字典配置显示技术职称和技术职称级别和学位
        const technicalTitle = responseData.data.technicalTitle;
        const technicalLevel = responseData.data.technicalLevel;
        const education = responseData.data.education;
        this.formData.technicalTitle = this.getDictLabel(this.dict.type.technical_title, technicalTitle);
        this.formData.technicalLevel = this.getDictLabel(this.dict.type.technical_level, technicalLevel);
        this.formData.education = this.getDictLabel(this.dict.type.education, education);
        this.queryParams.userId = responseData.data.userId; // 人员ID
        this.examQueryParams.userId = responseData.data.userId; // 人员ID
        this.getList();
        this.getExamRecords();
      });
    },
    getUserByUserId(userId) {
      this.formData = []
      getUser(userId).then(response => {
        console.log('user', response);
        this.formData.company = response.data.company; // 单位
        this.formData.name = response.data.nickName; // 姓名
        this.formData.gender = response.data.sex === '0' ? '男' : '女'; // 性别
        this.formData.birthDate = response.data.birthDate; // 出生年月
        this.formData.workStartDate = response.data.workDate; // 工作时间
        this.formData.deptName = response.data.dept.deptName; // 部门
        this.formData.postName = response.postGroup; // 岗位
        this.formData.major = response.data.major; // 专业
        this.formData.certificates = response.data.certificate; // 证书获取情况
        //根据字典配置显示技术职称和技术职称级别和学位
        const technicalTitle = response.data.technicalTitle;
        const technicalLevel = response.data.technicalLevel;
        const education = response.data.education;
        this.formData.technicalTitle = this.getDictLabel(this.dict.type.technical_title, technicalTitle);
        this.formData.technicalLevel = this.getDictLabel(this.dict.type.technical_level, technicalLevel);
        this.formData.education = this.getDictLabel(this.dict.type.education, education);
        this.examQueryParams.userId = userId; // 人员ID
        this.getList();
        this.getExamRecords();

      });
    },
    getDictLabel(options, value) {
      const item = options.filter(item => String(item.value) === String(value)); // 统一转为字符串
      return item.length > 0 ? item[0].label : '';
    },

    // 去除 HTML 标签，返回纯文本
    removeHtmlTags(text) {
      if (!text) return '';
      return text.replace(/<[^>]+>/g, ''); // 正则去除所有 HTML 标签
    },
    exportToExcel() {
      // 表单数据（每行两列：字段和对应的值）
      const formDataExport = [
        ["单位", this.formData.company, "姓名", this.formData.name],
        ["性别", this.formData.gender === "M" ? "男" : "女", "学历", this.formData.education],
        ["出生年月", this.formData.birthDate, "工作时间", this.formData.workStartDate],
        ["部门", this.formData.deptName, "岗位", this.formData.postName],
        ["技术职称", this.formData.technicalTitle, "技能等级", this.formData.technicalLevel],
        ["专业", this.formData.major, "证书获取情况", this.formData.certificates],
        [], // 空行用于分隔表单与表格
      ];

      // 表格数据
      const trainingDataExport = [
        ["培训日期", "培训内容", "详细内容", "培训方式", "培训层级", "考核结果"], // 表头
        ...this.trainingList.map((item) => [
          this.parseTime(item.trainingTime, "{y}-{m}-{d}"),
          this.removeHtmlTags(item.trainingContent),
          this.removeHtmlTags(item.trainingDetails || ""), // 假设详细内容字段存在
          this.getDictLabel(this.dict.type.training_method, item.trainingMethod),
          this.getDictLabel(this.dict.type.training_level, item.trainingLevel),
          this.getDictLabel(this.dict.type.assessment_result, item.result),
        ]),
      ];

      // 合并数据
      const combinedData = [...formDataExport, ...trainingDataExport];

      // 创建工作表
      const ws = XLSX.utils.aoa_to_sheet(combinedData);

      // 设置列宽（调整为与截图内容匹配的格式）
      const wsCols = [
        {wch: 20}, // 第一列宽度
        {wch: 30}, // 第二列宽度
        {wch: 20}, // 第三列宽度
        {wch: 30}, // 第四列宽度
        {wch: 20}, // 第五列宽度
        {wch: 20}, // 第六列宽度
      ];
      ws["!cols"] = wsCols;

      // 创建工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "从业人员安全教育培训档案");

      // 导出 Excel 文件
      const excelFile = XLSX.write(wb, {bookType: "xlsx", type: "array"});
      saveAs(new Blob([excelFile], {type: "application/octet-stream"}), "从业人员安全教育培训档案.xlsx");
    },
    // 辅助函数：格式化时间
    parseTime(time, cFormat) {
      if (!time) return "";
      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date = typeof time === "object" ? time : new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
      };
      const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a") return ["日", "一", "二", "三", "四", "五", "六"][value];
        return value.toString().padStart(2, "0");
      });
      return timeStr;
    },
  },
};
</script>

<style scoped>
/* 页面和容器的样式 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.export-button {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

table-title {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-title h3 {
  margin: 0;
  padding: 0;
  font-size: 20px;
  color: #333;
  border-bottom: 2px solid #ccc;
  padding-bottom: 5px;
}

.form-container {
  max-width: 100%;
  width: 100%;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-title1 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  text-align: center; /* 确保标题居中 */
}

.form {
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  flex-grow: 1; /* 填充剩余空间 */
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item label {
  font-size: 14px;
  color: #333;
}

.el-input, .el-radio-group, .el-date-picker {
  font-size: 14px;
  border-radius: 5px;
}

.el-radio-group .el-radio {
  font-size: 14px;
}

.el-table {
  margin-top: 30px;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

.el-table th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.el-table td {
  font-size: 14px;
}

.el-table .el-table__row:hover {
  background-color: #f5f5f5;
}

.el-table .el-table__header th {
  background-color: #f0f0f0;
}

.el-table .el-table__row {
  transition: background-color 0.3s ease;
}

.el-table .el-table__row:hover {
  background-color: #f1f9fc;
}

.el-table .el-table__cell {
  padding: 10px 15px;
}

/* 为表格添加滚动条样式 */
.training-table, .exam-records-table {
  max-height: 400px; /* 设置最大高度 */
  overflow-y: auto; /* 显示纵向滚动条 */
  border-radius: 4px; /* 可选，增加圆角 */
  margin-right: 10px; /* 确保右侧留有滚动条空间 */
}

/* 自定义滚动条样式 */
.training-table::-webkit-scrollbar, .exam-records-table::-webkit-scrollbar {
  width: 8px; /* 设置滚动条的宽度 */
}

.training-table::-webkit-scrollbar-thumb, .exam-records-table::-webkit-scrollbar-thumb {
  background-color: #888; /* 设置滚动条的颜色 */
  border-radius: 4px;
}

.training-table::-webkit-scrollbar-thumb:hover, .exam-records-table::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 设置滚动条 hover 时的颜色 */
}

</style>
